package com.gpj.learn.rocketmq.order;

import com.gpj.learn.rocketmq.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;

/**
 * @className OrderConsumer
 * @description
 *   顺序消息的消息消费者
 * @author GPJ
 * @date 2021/4/24 16:00
 * @version 1.0
 **/
@Slf4j
public class OrderConsumer {
	public static void main(String[] args) {
		DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("OderConsumerGroupName");
		consumer.setNamesrvAddr(CommonConstants.ROCKETMQ_NAMESERVER_ADDR);
		consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
		try {
			consumer.subscribe(CommonConstants.DEFAULT_TOPIC_NAME, "*");

			consumer.registerMessageListener((MessageListenerOrderly) (list, context) -> {
				context.setAutoCommit(true);
				for (MessageExt message : list) {
					log.info("接收到消息[{}]:{}", message.getMsgId(), new String(message.getBody(), StandardCharsets.UTF_8));
				}
				return ConsumeOrderlyStatus.SUCCESS;
			});

			consumer.start();
			log.info("consumer starting...");
		} catch (MQClientException e) {
			e.printStackTrace();
		}
	}
}
